package juc.Future;

import java.util.concurrent.*;

/**
 * @author 况祥彬
 * @date 2020/12/11 20:48
 **/

/**
 * 1.使用Callable+Future获取执行结果
 */
public class demo1 {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newCachedThreadPool();
        Task1 task = new Task1();
        Future<Integer> result = executor.submit(task);
        executor.shutdown();

        TimeUnit.SECONDS.sleep(2);
        System.out.println("主线程等待future线程执行完成");

        try {
            System.out.println("task运行结果"+result.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        System.out.println("所有任务执行完毕");
    }
}
class Task1 implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        System.out.println("子线程在进行计算");
        int sum = 0;
        for(int i=0;i<100;i++)
            sum += i;
        return sum;
    }
}

/**
 * 　2.使用Callable+FutureTask获取执行结果

 */
 class demo2 {
    public static void main(String[] args) throws InterruptedException {
        Task task = new Task();
        FutureTask<Integer> futureTask = new FutureTask<>(task);
        ExecutorService executorService = Executors.newCachedThreadPool();
        //法一
        Thread thread = new Thread(futureTask);
//        thread.start();
        //法二
        executorService.submit(futureTask);


        executorService.shutdown();



        TimeUnit.SECONDS.sleep(2);
        System.out.println("主线程等待future线程执行完成");

        try {                             //用futureTask来异步获取结果
            System.out.println("task运行结果"+futureTask.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        System.out.println("所有任务执行完毕");
    }
}
class Task implements Callable<Integer>{
    @Override
    public Integer call() throws Exception {
        System.out.println("子线程在进行计算");
        int sum = 0;
        for(int i=0;i<100;i++)
            sum += i;
        return sum;
    }
}